package com.itasura.java8;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * lambda性能对比
 *
 * @author sailor wang
 * @date 2018/11/28 2:38 PM
 * @description
 */
public class PerformanceTest {

    @Test
    public void test1() {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 1000000; i++)
            list.add(String.valueOf(i));
        //lambda表达式
        long start = System.currentTimeMillis();
        list.parallelStream().forEach((s) -> {
            s.toString();
        });
        long end1 = System.currentTimeMillis();
        System.out.println("lambda耗时：" + (end1 - start) + "  ms");

        //普通测试
//        for (String s : list) {
//            s.toString();
//        }
        long end2 = System.currentTimeMillis();

        System.out.println("普通耗时：" + (end2 - end1) + "  ms");

        //性能对比下来，单次循环: 普通for循环明显优于lambda表达式
    }

    @Test
    public void test2() {
        Thread.currentThread().setName("测试线程");
        long threadid = Thread.currentThread().getId();
        System.out.println("threadid -> "+threadid);
        List<String> strList = initList(100000);
        for (int i = 1; i < 12; i++) {
            System.out.println("--------------------第" + i + "次");
            long t1 = System.nanoTime();
            testLambda(strList);
            long t2 = System.nanoTime();
            testForeach(strList);
            long t3 = System.nanoTime();
            System.out.println("lambda---" + (t2 - t1) / 1000 + "μs");
            System.out.println("增强for--" + (t3 - t2) / 1000 + "μs");
        }
        //性能对比下来，循环多次: lambda表达式for循环优于普通for循环
    }

    /**
     * 增强for测试
     *
     * @param strList
     */
    private static void testForeach(List<String> strList) {
        for (String str : strList) {
            str.hashCode();
        }
    }


    /**
     * lambda forEach测试
     *
     * @param strList
     */
    private static void testLambda(List<String> strList) {
        strList.forEach(str -> str.hashCode());
        //strList.stream().forEach(str -> str.hashCode());
    }

    /**
     * 初始化测试集合
     *
     * @param size
     * @return
     */
    private static List<String> initList(int size) {
        List<String> strList = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            strList.add(UUID.randomUUID().toString());
        }
        return strList;
    }
}